package controller.expertInfo.adminEdit;

import base.response.OffsetLimitPage;
import base.response.Select2;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import controller.common.BaseController;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import services.dictionary.ItemTypeServices;
import services.expertInfo.ExpertBaseServices;
import services.expertInfo.ExpertCertificateServices;
import services.expertInfo.ExpertCompanyServices;
import services.specific.AdminManageExpertInfoServices;
import util.DateUtil;
import util.IfElseUtil;
import util.io.PoiExcelCreateUtil;
import wt.entity.dictionary.ItemType;
import wt.entity.expertInfo.*;
import wt.entity.specific.AdminManageExpertInfo;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

;

/**
 * 功能:
 * 作者: 洪世成
 * 日期: 2017/9/9
 * 版权所有: admin
 */
@Controller
@RequestMapping("expertInfo/adminEdit")
public class IndexController extends BaseController {

    @Autowired
    ExpertBaseServices expertBaseServices;
    @Autowired
    AdminManageExpertInfoServices adminManageExpertInfoServices;
    @Autowired
    ExpertCompanyServices expertCompanyServices;
    @Autowired
    ExpertCertificateServices expertCertificateServices;
    @Autowired
    ItemTypeServices itemTypeServices;

    @RequiresPermissions("expertInfo:adminEdit:default")
    @RequestMapping("index")
    public String index() {
        return "expertInfo/adminEdit/index";
    }


    @RequiresPermissions("expertInfo:adminEdit:default")
    @ResponseBody
    @RequestMapping("select")
    public OffsetLimitPage selectForMainShow(
            String expertName,
            String idCard,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date birthday,
            Short education,
            Short outLander,
            Integer assessCount,
            @RequestParam(value = "certificateTypeIdList[]", required = false) List<String> certificateTypeIdList,
            @RequestParam(value = "majorTypeIdList[]", required = false) List<String> majorTypeIdList,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date certificateValidDate,
            String affiliate,

            Integer offset,
            Integer limit) throws Exception {

        PageHelper.offsetPage(offset, limit);
        List<AdminManageExpertInfo> adminManageExpertInfoList = adminManageExpertInfoServices.select(expertName, idCard, birthday, education, outLander, assessCount, certificateTypeIdList, majorTypeIdList, certificateValidDate, affiliate);


        if (!adminManageExpertInfoList.isEmpty()) {

            List<String> expertIdList = ExpertBase.getIdList(adminManageExpertInfoList);

            ExpertCertificateExample expertCertificateExample = new ExpertCertificateExample();
            expertCertificateExample.setOrderByClause("ITEM_ID");
            expertCertificateExample.createCriteria().andExpertIdIn(expertIdList);
            List<ExpertCertificate> expertCertificateList = expertCertificateServices.selectByExample(expertCertificateExample);
            List<ItemType> itemTypeList = itemTypeServices.selectByExample(null);
            for (ExpertCertificate expertCertificate : expertCertificateList) {
                for (ItemType itemType : itemTypeList) {
                    if (expertCertificate.getItemId().equals(itemType.getId())) {
                        expertCertificate.setItemType(itemType);
                        break;
                    }
                }
            }

            for (ExpertCertificate expertCertificate : expertCertificateList) {
                for (AdminManageExpertInfo adminManageExpertInfo : adminManageExpertInfoList) {
                    if (expertCertificate.getExpertId().equals(adminManageExpertInfo.getId())) {
                        adminManageExpertInfo.getExpertCertificateList().add(expertCertificate);
                        break;
                    }
                }
            }

            ExpertCompanyExample expertCompanyExample = new ExpertCompanyExample();
            expertCompanyExample.createCriteria().andExpertIdIn(expertIdList);
            List<ExpertCompany> expertCompanyList = expertCompanyServices.selectByExample(expertCompanyExample);
            for (ExpertCompany expertCompany : expertCompanyList) {
                for (AdminManageExpertInfo adminManageExpertInfo : adminManageExpertInfoList) {
                    if (expertCompany.getExpertId().equals(adminManageExpertInfo.getId())) {
                        adminManageExpertInfo.setExpertCompany(expertCompany);
                        break;
                    }
                }
            }

        }

        return new OffsetLimitPage((Page) adminManageExpertInfoList);
    }


    @RequiresPermissions("expertInfo:adminEdit:default")
    @ResponseBody
    @RequestMapping("exportExcel")
    public void exportExcel(
            String expertName,
            String idCard,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date birthday,
            Short education,
            Short outLander,
            Integer assessCount,
            String certificateTypeIdList,
            String majorTypeIdList,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date certificateValidDate,
            String affiliate,
            HttpServletResponse response
    ) throws Exception {

        List<String> certificateTypeIdListList = null;
        List<String> majorTypeIdListList = null;
        if (!StringUtils.isBlank(majorTypeIdList)) {
            majorTypeIdListList = Arrays.asList(majorTypeIdList.split(","));
        }

        if (!StringUtils.isBlank(certificateTypeIdList)) {
            certificateTypeIdListList = Arrays.asList(certificateTypeIdList.split(","));
        }

        OffsetLimitPage offsetLimitPage = selectForMainShow(expertName, idCard, birthday, education, outLander, assessCount, certificateTypeIdListList, majorTypeIdListList, certificateValidDate, affiliate, 0, 9999);
        List<AdminManageExpertInfo> adminManageExpertInfoList = offsetLimitPage.getRows();

        List<Map> mapList = new ArrayList<Map>(adminManageExpertInfoList.size());
        for (AdminManageExpertInfo info : adminManageExpertInfoList) {
            Map map = new HashMap();
            map.put("name", info.getName());
            map.put("idCard", info.getIdCard());
            map.put("phone", info.getPhone());
            map.put("birthday", DateUtil.date2String(info.getBirthday(), DateUtil.DATE_PATTEN));
            if (info.getOutLander() != null) {
                map.put("outLander", IfElseUtil.ifElse(
                        info.getOutLander() == 1, "省外",
                        info.getOutLander() == 0, "省内")
                );
            }


            StringBuffer stringBuffer = new StringBuffer();
            for (ExpertCertificate certificate : info.getExpertCertificateList()) {
                stringBuffer.append(certificate.getItemType().getName());
                stringBuffer.append("：");
                stringBuffer.append(certificate.getGrade());
                stringBuffer.append("；");
            }
            if (stringBuffer.length() > 1) {
                map.put("expertType", stringBuffer.toString().substring(0, stringBuffer.length() - 1));
            }

            if (info.getExpertCompany() != null) {
                map.put("companyName", info.getExpertCompany().getName());
                map.put("companyAffiliate", info.getExpertCompany().getAffiliate());
                map.put("companyAddress", info.getExpertCompany().getAddress());
            }
            map.put("assessCount", info.getAssessCount());
            mapList.add(map);
        }
        PoiExcelCreateUtil poi = new PoiExcelCreateUtil(10);
        CellStyle headStyle = poi.createCellStyle(PoiExcelCreateUtil.FONT_HEIGHT_DEFAULT, PoiExcelCreateUtil.FONT_WEIGHT_BOLE, PoiExcelCreateUtil.FONT_NAME_SONG, null);
        CellStyle bodyStyle = poi.createCellStyle(PoiExcelCreateUtil.FONT_HEIGHT_DEFAULT, PoiExcelCreateUtil.FONT_WEIGHT_NORMAL, PoiExcelCreateUtil.FONT_NAME_SONG, null);
        poi.createSheet("sheet1",
                null,
                new String[]{"姓名", "身份证号", "联系方式", "出生日期", "是否省外", "专家类型", "单位名称", "所属单位", "单位地址", "评审次数"},
                new String[]{"name", "idCard", "phone", "birthday", "outLander", "expertType", "companyName", "companyAffiliate", "companyAddress", "assessCount"},
                new int[]{4000, 8000, 6000, 8000, 4000, 4000, 4000, 4000, 4000, 4000},
                null, headStyle,
                new CellStyle[]{bodyStyle, bodyStyle, bodyStyle, bodyStyle, bodyStyle, bodyStyle, bodyStyle, bodyStyle, bodyStyle, bodyStyle},
                mapList
        );

        poi.write2Response(response, "专家信息_" + DateUtil.date2String(new Date(),"yyyy-MM-dd_HH-mm-ss"));


    }


    @RequiresPermissions("expertInfo:adminEdit:show")
    @RequestMapping("expertInfoFrame")
    public String expertInfoFrame(String id, Map map) {
        map.put("id", id);
        return "expertInfo/adminEdit/expertInfoFrame";
    }


    @ResponseBody
    @RequestMapping(value = {"selectExpertByLikeName"})
    public Select2 addManagerAssess(@RequestParam(defaultValue = "") String q, @RequestParam(defaultValue = "1") Integer page) throws Exception {

        Select2 select2 = new Select2();
        PageHelper.startPage(page, 30);
        List<ExpertBase> expertBaseList = new ArrayList<ExpertBase>();
        if (StringUtils.isBlank(q)) {
            expertBaseList = expertBaseServices.selectByExample(null);
        } else {
            q = "%" + q.trim() + "%";
            ExpertBaseExample expertBaseExample = new ExpertBaseExample();
            expertBaseExample.createCriteria().andNameLike(q);
            expertBaseList = expertBaseServices.selectByExample(expertBaseExample);
        }

        for (ExpertBase expertBase : expertBaseList) {
            select2.putItem(expertBase.getId(), expertBase.getName(), expertBase.getIdCard());
        }

        select2.setTotal_count(((Page<ExpertBase>) expertBaseList).getTotal());
        return select2;
    }


}
